package com.genesis.yunnanji.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.cb.ratingbar.CBRatingBar;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.adapter.SupSpecialAdapter;
import com.genesis.yunnanji.bean.SupBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.utils.NetWorkUtils;
import com.genesis.yunnanji.view.TextBottomActionSheet;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.json.JSONObject;
import org.michaelbel.bottomsheet.BottomSheet;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.net.URISyntaxException;

import es.dmoral.toasty.Toasty;

public class SupDetails extends BaseActivity {
    @ViewInject(R.id.toolbar_supdetails_toolbar)
    private Toolbar mToolbar;
    private String supid;
    private ImageView bg;
    private TextView tvName;
    private TextView tvPhone;
    private TextView tvAddress;
    private TextView tvOpenTime;
    private TextView tvIntro;
    private TextView tvTitle;
    private TextView tvNavigation;
    private CBRatingBar ratingBar;
    private RecyclerView mRecyclerView;
    private MapView mMapView;
    private AMap mAmap;
    private NestedScrollView scrollView;
    private double lat;
    private double lon;
    private String address;
    private TextView tvFaxes;

    private TextView tvExperienceContent;
    private TextView tvProductSource;
    private TextView tvProductProcess;
    private TextView tvUseWay;
    private RecyclerView rvDiscuss;

    Intent intent;
    private int[] items1 = new int[]{
            R.string.baidu,
            R.string.gaode,
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_supdetails);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.main_color), 2);
        supid = getIntent().getStringExtra("supid");
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        bg = (ImageView) findViewById(R.id.iv_supdetails_backdrop);
        tvName = (TextView) findViewById(R.id.tv_supdetails_name);
        ratingBar = (CBRatingBar) findViewById(R.id.rb_supdetails_rating);
        tvPhone = (TextView) findViewById(R.id.tv_supdetails_phone);
        tvAddress = (TextView) findViewById(R.id.tv_supdetails_address);
        tvOpenTime = (TextView) findViewById(R.id.tv_supdetails_time);
        tvIntro = (TextView) findViewById(R.id.tv_supdetails_intro);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_supdetails_rv);
        scrollView = (NestedScrollView) findViewById(R.id.nsv_supdetail_scrollview);
        mMapView = (MapView) findViewById(R.id.map_supdetails_map);
        tvTitle = (TextView) findViewById(R.id.tv_supdetails_title);
        tvFaxes = (TextView) findViewById(R.id.tv_faxes);
        tvNavigation = (TextView) findViewById(R.id.tv_supdetails_navigation);

        tvExperienceContent = (TextView) findViewById(R.id.tvExperienceContent);
        tvProductSource = (TextView) findViewById(R.id.tvProductSource);
        tvProductProcess = (TextView) findViewById(R.id.tvProductProcess);
        tvUseWay = (TextView) findViewById(R.id.tvUseWay);
        rvDiscuss = (RecyclerView) findViewById(R.id.rvDiscuss);

        mMapView.onCreate(savedInstanceState);
        if (mAmap == null) {
            mAmap = mMapView.getMap();
        }
    }

    @Override
    protected void setUpView() {
        ratingBar.setPathData(getResources().getString(R.string.round_star))//传入path的数据
                .setPathDataId(R.string.round_star);//传入path数据id
        getData(null);
    }

    private void getData(final TwinklingRefreshLayout refreshLayout) {
//        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.SUP_DETAILS);
        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.INFOSPACE_DETAILS);
        params.addBodyParameter("id", supid + "");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Gson gson = new Gson();
//                Log.e("lk+++", "onSuccess: " + jsonObject.toString());
                SupBean supBean = gson.fromJson(jsonObject.toString(), SupBean.class);
                setData(supBean);

            }

            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {
                if (refreshLayout != null) {
                    refreshLayout.finishRefreshing();
                    refreshLayout.finishLoadmore();
                }
            }

            @Override
            public void onError(String errorStr) {

            }
        });
    }

    private void setData(final SupBean supBean) {
        tvTitle.setText(supBean.getResult().getInfo().getTitle());
        x.image().bind(bg, GenesisApiConfig.PIC_HOST + supBean.getResult().getInfo().getApp_cover_img().get(0));
        genesisUtils.setNotNullText(tvName, supBean.getResult().getInfo().getTitle(), false);
        genesisUtils.setNotNullText(tvPhone, supBean.getResult().getInfo().getPhone(), false);
        genesisUtils.setNotNullText(tvFaxes, supBean.getResult().getInfo().getPhone(), false);

        genesisUtils.setNotNullText(tvExperienceContent, supBean.getResult().getInfo().getTiyan_desc(), false);
        tvExperienceContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TextBottomActionSheet(SupDetails.this, "体验内容", supBean.getResult().getInfo().getTiyan_desc()).show();
            }
        });
        genesisUtils.setNotNullText(tvProductSource, supBean.getResult().getInfo().getChanpin_desc(), false);
        tvProductSource.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TextBottomActionSheet(SupDetails.this, "产品来源", supBean.getResult().getInfo().getChanpin_desc()).show();
            }
        });
        genesisUtils.setNotNullText(tvProductProcess, supBean.getResult().getInfo().getJiagong_desc(), false);
        tvProductProcess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TextBottomActionSheet(SupDetails.this, "产品加工", supBean.getResult().getInfo().getJiagong_desc()).show();
            }
        });
        genesisUtils.setNotNullText(tvUseWay, supBean.getResult().getInfo().getShiyong_desc(), false);
        tvUseWay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TextBottomActionSheet(SupDetails.this, "使用方法", supBean.getResult().getInfo().getShiyong_desc()).show();
            }
        });
//        rvDiscuss.setAdapter(SupDiscussAdapter);

        genesisUtils.setNotNullText(tvAddress, supBean.getResult().getInfo().getAddress(), false);
        genesisUtils.setNotNullText(tvOpenTime, supBean.getResult().getInfo().getShop_time(), false);
        genesisUtils.setNotNullText(tvIntro, supBean.getResult().getInfo().getDescription(), false);

        ratingBar.setStarProgress(Float.valueOf(supBean.getResult().getInfo().getRecommend()));
        SupSpecialAdapter adapter = new SupSpecialAdapter(context, supBean.getResult().getProduct());
        mRecyclerView.setLayoutManager(new GridLayoutManager(context, 2));
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setAdapter(adapter);
        setupmap(Double.parseDouble(supBean.getResult().getInfo().getLng()), Double.parseDouble(supBean.getResult().getInfo().getLat()));
        address = supBean.getResult().getInfo().getAddress();
        lat = Double.parseDouble(supBean.getResult().getInfo().getLng());
        lon = Double.parseDouble(supBean.getResult().getInfo().getLat());
        tvNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BottomSheet.Builder builder = new BottomSheet.Builder(context);
                builder.setItems(items1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                if (genesisUtils.isAvilible(context, "com.baidu.BaiduMap")) {
                                    try {
                                        intent = Intent.getIntent("intent://map/direction?origin=我的位置&destination=" + address + "&mode=driving&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                                        context.startActivity(intent);
                                    } catch (URISyntaxException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    Toasty.error(context, "您尚未安装百度地图").show();
                                }
                                break;
                            case 1:
                                if (genesisUtils.isAvilible(context, "com.autonavi.minimap")) {
                                    try {
                                        intent = Intent.getIntent("androidamap://route?sourceApplication=softname&sname=我的位置&dlat=" + lat + "&dlon=" + lon + "&dname=" + address + "&dev=0&m=0&t=1");
                                        context.startActivity(intent);
                                    } catch (URISyntaxException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    Toasty.error(context, "您尚未安装高德地图").show();
                                }
                                break;
                        }
                    }
                });
                builder.setDividers(true);
                builder.show();
            }
        });
    }


    public void setupmap(final Double lat, final Double lng) {
        LatLng latLng = new LatLng(lat, lng);
        mAmap.addMarker(new MarkerOptions().position(latLng).draggable(false));
        mAmap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
        mAmap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                int action = motionEvent.getAction();
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        scrollView.requestDisallowInterceptTouchEvent(false);
                        break;
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        scrollView.requestDisallowInterceptTouchEvent(true);
                        break;
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
}
